import 'package:fate_blind_box/utils/loading.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../../theme/theme_color.dart';
import '../../../utils/common_widget.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

import 'address_chose_search_controller.dart';
import 'adress_chose_poi_model.dart';
import 'package:get/get.dart';

class AddressChoseSearchPage extends StatelessWidget {
  Function? finishBlock;

  AddressChoseSearchPage({Key? key, this.finishBlock}) : super(key: key);
  AddressChoseSearchController addressChoseSearchController =
      Get.put(AddressChoseSearchController());
  TextEditingController inputVC = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return AppWidget.navTitleBar(
      bgColor: ThemeColor.grayF9F9F9Color,
      title: '选择地址',
      childWidget: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: Column(
          children: [
            Container(
              color: Colors.white,
              margin: const EdgeInsets.symmetric(
                vertical: 10,
              ),
              child: Row(
                children: [
                  Expanded(
                    child: TextField(
                      controller: inputVC,
                      onChanged: (res) {},
                      onSubmitted: (res) {
                        startSearch();
                      },
                      textInputAction: TextInputAction.search,
                      cursorColor: ThemeColor.appColor,
                      decoration: InputDecoration(
                        prefixIcon: UnconstrainedBox(
                            child: Image.asset(
                          'images/map/search_mirror_big.png',
                          width: 15,
                        )),
                        border: InputBorder.none,
                        hintText: '搜索',
                        hintStyle: const TextStyle(
                          fontSize: 16,
                          color: Color(0xFFB3B3B3),
                        ),
                      ),
                    ),
                  ),
                  UnconstrainedBox(
                    child: CupertinoButton(
                      padding: EdgeInsets.zero,
                      onPressed: () {
                        startSearch();
                      },
                      child: Container(
                        margin: const EdgeInsets.only(right: 15),
                        width: 54,
                        height: 31,
                        decoration: BoxDecoration(
                          color: ThemeColor.appColor,
                          borderRadius: BorderRadius.circular(5),
                        ),
                        alignment: Alignment.center,
                        child: const Text(
                          '搜索',
                          style: TextStyle(color: Colors.white, fontSize: 16),
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
            Expanded(
              child: GetBuilder(
                  id: addressChoseSearchController.poiViewId,
                  builder: (AddressChoseSearchController choseController) {
                    return ListView.builder(
                        itemCount: choseController.addressList.length,
                        itemBuilder: (BuildContext context, int index) {
                          AddressChosePoiDataModel chosePoiModel =
                              choseController.addressList[index];
                          return itemView(chosePoiModel);
                        });
                  }),
            )
          ],
        ),
      ),
    );
  }

  //开始搜索
  void startSearch() {
    String searchText = inputVC.text;
    if (searchText.isEmpty) {
      toast('请输入内容');
      return;
    }
    if (addressChoseSearchController.addressList.isNotEmpty) {
      addressChoseSearchController.addressList.clear();
    }

    fetchNearbyPlaces(searchText);
  }

  fetchNearbyPlaces(String keyWords) async {
    final apiKey = '1761005a13eece489b7a82787464fde0';
    final url =
        'https://restapi.amap.com/v3/place/text?keywords=$keyWords&offset=20&page=1&key=$apiKey&extensions=all';
    print('请求$url');
    final response = await http.get(Uri.parse(url));
    if (response.statusCode == 200) {
      final jsonData = json.decode(response.body);
      AddressChosePoiModel chosePoiModel =
          AddressChosePoiModel.fromJson(jsonData);
      List<AddressChosePoiDataModel> poiList = chosePoiModel.poi ?? [];
      for (int i = 0; i < poiList.length; i++) {
        AddressChosePoiDataModel poiDataModel = poiList[i];
        poiDataModel.isChose = i == 0;
        addressChoseSearchController.addressList.add(poiDataModel);
      }
      addressChoseSearchController
          .update([addressChoseSearchController.poiViewId]);
      // 在jsonData中处理周边信息
      print('拿到的数据$jsonData');
    } else {
      throw Exception('Failed to load nearby places');
    }
  }

  Widget itemView(AddressChosePoiDataModel chosePoiModel) {
    return GestureDetector(
      //padding: EdgeInsets.zero,
      onTap: () {
        if (chosePoiModel.isChose) {
          return;
        }
        addressChoseSearchController.addressList.forEach((element) {
          if (element.address == chosePoiModel.address) {
            element.isChose = true;
          } else {
            element.isChose = false;
          }
        });
        addressChoseSearchController
            .update([addressChoseSearchController.poiViewId]);
      },
      child: Stack(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                alignment: Alignment.topLeft,
                color: Colors.white,
                height: 42,
                padding: const EdgeInsets.only(left: 14, top: 10),
                child: Text(
                  chosePoiModel.name ?? '',
                  style: TextStyle(fontSize: 16.sp, color: Colors.black),
                ),
              ),
              Container(
                color: ThemeColor.dividerColor,
                height: 1,
              ),
            ],
          ),
          Positioned(
            top: 0,
            bottom: 0,
            right: 16,
            child: Visibility(
              visible: chosePoiModel.isChose,
              child: GestureDetector(
                onTap: () {
                  AddressChosePoiDataModel choseModel =
                      addressChoseSearchController.addressList
                          .singleWhere((element) => element.isChose);
                  if (finishBlock != null) {
                    finishBlock!(choseModel);
                  }
                  Get.back();
                  Get.back();
                },
                child: Center(
                  child: Text(
                    '确定',
                    style: TextStyle(fontSize: 14, color: ThemeColor.appColor),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
